package com.lagou.homework.zookeeper;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author shiyuhou
 * @version 1.0
 * @description: TODO
 * @date 6/22/21 5:57 PM
 */
public class CustomDruidDataSource {

    public static String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&connectTimeout=0&socketTimeout=0";
    public static String username="root";
    public static String password="12345678";

    /**
     * @description: 初始化连接配置
     * @return: java.util.Properties
     * @author shiyuhou
     * @date: 6/27/21 12:50 AM
     */
    public static Properties initProperties(){
        Properties properties=new Properties();
        properties.setProperty("url",url);
        properties.setProperty("username",username);
        properties.setProperty("password",password);
        return properties;
    }

    /**
     * @description: 通过druid获取mysql数据源
     * @return: javax.sql.DataSource
     * @author shiyuhou
     * @date: 6/26/21 11:46 PM
     */
    public static DruidDataSource getDataSource(Properties properties){

        DruidDataSource dataSource=null;

        try {
            dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dataSource;
    }

    public static void main(String[] args) throws SQLException {

        DataSource dataSource = getDataSource(initProperties());
        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("show tables;");
        while(rs.next()) {
            System.out.println(rs.getString(1));
        }
        if(rs!=null)
            rs.close();
        if(stmt!=null)
            stmt.close();
        if(conn!=null)
            conn.close();

    }
}
